import 'dart:io';
import 'package:base_lib/common/index.dart';
import 'package:base_lib/index.dart';
import 'package:doctor_inquiry_lib/constant/constant.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import '../entity/MessageNormal.dart';
import 'bubble.dart';
import 'voice_animation.dart';

class ChatMessageItem extends StatefulWidget {
  final WMessage mMessage;
  final ValueSetter<WVoiceMessage> onAudioTap;
  final ValueSetter<WCardMessage> onCardTap;

  ChatMessageItem({Key key, this.mMessage, this.onAudioTap, this.onCardTap})
      : super(key: key);

  @override
  ChatMessageItemState createState() => ChatMessageItemState();
}

class ChatMessageItemState extends State<ChatMessageItem> {
  List<String> mAudioAssetRightList = new List();
  List<String> mAudioAssetLeftList = new List();

  bool mIsPlaying = false;
  String mUUid = "";

  methodInChild(bool isPlay, String uid) {
    mIsPlaying = isPlay;
    mUUid = uid;
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    mAudioAssetRightList
        .add(Constant.ASSETS_IMG_CHAT + "audio_animation_list_right_1.png");
    mAudioAssetRightList
        .add(Constant.ASSETS_IMG_CHAT + "audio_animation_list_right_2.png");
    mAudioAssetRightList
        .add(Constant.ASSETS_IMG_CHAT + "audio_animation_list_right_3.png");
    mAudioAssetLeftList
        .add(Constant.ASSETS_IMG_CHAT + "audio_animation_list_left_1.png");
    mAudioAssetLeftList
        .add(Constant.ASSETS_IMG_CHAT + "audio_animation_list_left_2.png");
    mAudioAssetLeftList
        .add(Constant.ASSETS_IMG_CHAT + "audio_animation_list_left_3.png");
  }

  @override
  Widget build(BuildContext context) {
    return new Container(
      margin: const EdgeInsets.symmetric(vertical: 10.0),
      child: widget.mMessage.msgType == WMessageType.hint ||
              widget.mMessage.msgType == WMessageType.sys
          ? getHintMessageLayout()
          : widget.mMessage.isSend
              ? getSentMessageLayout()
              : getReceivedMessageLayout(),
    );
  }

  Widget getMImageLayout(WImageMessage mMessage) {
    Widget image;
    bool isFile = false;
    if (mMessage.thumbPath == null || mMessage.thumbPath.isEmpty) {
      image =
          Image.asset(('${(widget.mMessage as WImageMessage).placeholder}'));
      isFile = true;
    } else if (mMessage.thumbPath.contains("http://") ||
        mMessage.thumbPath.contains("https://")) {
      image = Image.network(
        '${(widget.mMessage as WImageMessage).thumbPath}',
        fit: BoxFit.fill,
      );
    } else {
      image = Image.file(
        File((widget.mMessage as WImageMessage).thumbPath),
        fit: BoxFit.fill,
      );
    }

    return GestureDetector(
      onTap: () {
        ShowImgDialogUtil.showImgDialog(
            context, (widget.mMessage as WImageMessage).path);
      },
      child: image,
    );
  }

  Widget getItemContent(WMessage mMessage) {
    switch (mMessage.msgType) {
      case WMessageType.text:
        return Text(
          '${(widget.mMessage as WTextMessage).text}',
          softWrap: true,
          style: TextStyle(fontSize: 14.0, color: Colors.black),
        );
        break;
      case WMessageType.sys:
        //todo 系统消息展示时间，做对应操作
        return Text(
          '${TimelineUtil.formatA(widget.mMessage.createTime)}',
          softWrap: true,
          textAlign: TextAlign.center,
          style: TextStyle(fontSize: 12.0, color: Colors.grey),
        );
        break;
      case WMessageType.hint:
        return Text(
          '${(widget.mMessage as WHintMessage).hint}',
          softWrap: true,
          textAlign: TextAlign.center,
          style: TextStyle(fontSize: 12.0, color: Colors.grey),
        );
        break;
      case WMessageType.card:
        // FLog('card  ${(widget.mMessage as WCardMessage).toJson()}');
        return GestureDetector(
          onTap:(){
            widget.onCardTap?.call(widget.mMessage as WCardMessage);
          },
          child: Container(
            width: ScreenAdapter.screenWidthDp * 0.5,
            height: 80,
            decoration: BoxDecoration(
                color: Colors.green, borderRadius: BorderRadius.circular(15)),
            child: Column(
              children: [
                Expanded(
                    child: Row(
                  children: [
                    10.hGapDp,
                    Expanded(
                      child: Text(
                        '${(widget.mMessage as WCardMessage).title}',
                        softWrap: true,
                        textAlign: TextAlign.left,
                        style: TextStyle(fontSize: 12.0, color: Colors.white),
                      ),
                    ),
                    10.hGapDp,
                  ],
                )),
                Expanded(
                  child: Container(
                      color: Colors.white,
                      child: Row(
                        children: [
                          10.hGapDp,
                          Text(
                            '查看详情',
                            softWrap: true,
                            textAlign: TextAlign.left,
                            style:
                                TextStyle(fontSize: 12.0, color: Colors.blue),
                          ),
                          Spacer(),
                          Icon(
                            Icons.arrow_forward_ios_rounded,
                            size: 14,
                            color: Colors.grey,
                          ),
                          10.hGapDp,
                        ],
                      )),
                )
              ],
            ),
          ),
        );

        break;
      case WMessageType.image:
        // FLog((widget.mMessage as WImageMessage).toJson());
        return Container(
          constraints: BoxConstraints(
            maxWidth: ScreenAdapter.screenWidthDp * 0.4,
            maxHeight: ScreenAdapter.screenWidthDp * 0.4,
          ),
          child: getMImageLayout(widget.mMessage as WImageMessage),
        );
        break;
      case WMessageType.voice:
        bool isStop = true;
        if (mUUid == widget.mMessage.msgID) {
          if (!mIsPlaying) {
            isStop = true;
          } else {
            isStop = false;
          }
        } else {
          isStop = true;
        }
        //    print("是否停止:"+isStop.toString()+"chat_room_c2c.widget.mUUid=:"+chat_room_c2c.widget.mUUid );
        return Container(
          constraints:
              BoxConstraints(maxWidth: ScreenAdapter.screenWidthDp * 0.5),
          child: GestureDetector(
            onTap: () {
              widget.onAudioTap(widget.mMessage as WVoiceMessage);
            },
            child: VoiceAnimationImage(
              mMessage.isSend ? mAudioAssetRightList : mAudioAssetLeftList,
              isLeft: !mMessage.isSend,
              width: 45,
              height: 30,
              isStop: isStop,
            ),
          ),
        );
        break;
      default:
        return Text(
          '[暂不支持的消息]',
          softWrap: true,
          style: TextStyle(fontSize: 14.0, color: Colors.black),
        );
        break;
    }
  }

  BubbleStyle getItemBundleStyle(WMessage mMessage) {
    BubbleStyle styleSendText = BubbleStyle(
      nip: BubbleNip.rightText,
      color: Color(0xffCCEAFF),
      nipOffset: 5,
      nipWidth: 10,
      nipHeight: 10,
      margin: BubbleEdges.only(left: 50.0),
      padding: BubbleEdges.only(top: 8, bottom: 10, left: 15, right: 10),
    );
    BubbleStyle styleSendImg = BubbleStyle(
      nip: BubbleNip.noRight,
      color: Colors.transparent,
      nipOffset: 5,
      nipWidth: 10,
      nipHeight: 10,
      margin: BubbleEdges.only(left: 50.0),
    );

    BubbleStyle styleReceiveText = BubbleStyle(
      nip: BubbleNip.leftText,
      color: Colors.white,
      nipOffset: 5,
      nipWidth: 10,
      nipHeight: 10,
      margin: BubbleEdges.only(right: 50.0),
      padding: BubbleEdges.only(top: 8, bottom: 10, left: 10, right: 15),
    );

    BubbleStyle styleReceiveImg = BubbleStyle(
      nip: BubbleNip.noLeft,
      color: Colors.transparent,
      nipOffset: 5,
      nipWidth: 10,
      nipHeight: 10,
      margin: BubbleEdges.only(left: 50.0),
    );

    switch (mMessage.msgType) {
      case WMessageType.hint:
        return null;
        break;
      case WMessageType.text:
        return widget.mMessage.isSend ? styleSendText : styleReceiveText;
        break;
      case WMessageType.card:
        return widget.mMessage.isSend ? styleSendImg : styleSendImg;
        break;
      case WMessageType.image:
        return widget.mMessage.isSend ? styleSendImg : styleReceiveImg;
        break;
      case WMessageType.voice:
        return widget.mMessage.isSend ? styleSendText : styleReceiveText;
        break;
      default:
        return widget.mMessage.isSend ? styleSendText : styleReceiveText;
        break;
    }
  }

  Widget getHintMessageLayout() {
    return Container(
      alignment: Alignment.center,
      constraints: BoxConstraints(
        maxWidth: MediaQuery.of(context).size.width * 0.8,
      ),
      child: getItemContent(widget.mMessage),
      margin: EdgeInsets.only(bottom: 10, top: 10),
    );
  }

  Widget getSentMessageLayout() {
    return Container(
        alignment: Alignment.centerRight,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Visibility(
              visible: widget.mMessage.state != WMessageState.send_succeed,
              child: Container(
                  child: Text(
                widget.mMessage.state == WMessageState.sending
                    ? "发送中..."
                    : widget.mMessage.state == WMessageState.send_failed
                        ? '发送失败'
                        : "",
                style: TextStyle(fontSize: 14, color: Colors.red),
              )),
            ),
            Visibility(
              visible: widget.mMessage.msgType == WMessageType.voice,
              child: Container(
                child: widget.mMessage.msgType == WMessageType.voice
                    ? Text(
                        "${(widget.mMessage as WVoiceMessage).duration}''",
                        style: TextStyle(fontSize: 14, color: Colors.black),
                      )
                    : new Container(),
              ),
            ),
            Container(
              constraints: BoxConstraints(
                maxWidth: MediaQuery.of(context).size.width * 0.8,
              ),
              child: Bubble(
                style: getItemBundleStyle(widget.mMessage),
                child: getItemContent(widget.mMessage),
              ),
              margin: EdgeInsets.only(
                bottom: 5.0,
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(right: 10.0, left: 5),
              child: ClipRRect(
                child: PlaceholderImage(
                  width: 30,
                  height: 30,
                  placeholder: '${Constant.ASSETS_IMG_CHAT}public_avatar.png',
                  imgUrl: widget.mMessage?.from?.headUrl ?? '',
                ),
                borderRadius: BorderRadius.circular(15),
              ),
            ),
          ],
        ));
  }

  Widget getReceivedMessageLayout() {
    return Container(
        alignment: Alignment.centerLeft,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(right: 5.0, left: 10),
              child: ClipRRect(
                child: PlaceholderImage(
                  width: 30,
                  height: 30,
                  placeholder: '${Constant.ASSETS_IMG_CHAT}public_avatar.png',
                  imgUrl: widget.mMessage?.from?.headUrl ?? '',
                ),
                borderRadius: BorderRadius.circular(15),
              ),
            ),
            Container(
              constraints: BoxConstraints(
                maxWidth: MediaQuery.of(context).size.width * 0.8,
              ),
              child: Bubble(
                style: getItemBundleStyle(widget.mMessage),
                child: getItemContent(widget.mMessage),
              ),
              margin: EdgeInsets.only(
                bottom: 5.0,
              ),
            ),
            Visibility(
              visible: widget.mMessage.msgType == WMessageType.voice,
              child: Container(
                child: widget.mMessage.msgType == WMessageType.voice
                    ? Text(
                        "${(widget.mMessage as WVoiceMessage).duration}''",
                        style: TextStyle(fontSize: 14, color: Colors.black),
                      )
                    : new Container(),
              ),
            ),
          ],
        ));
  }
}
